package com.icoolkj.learn.juc.base;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @author icoolkj
 * @version 1.0
 * @description 创建和启动线程案例
 * @createDate 2025/03/04 09:11
 */
public class NewThread {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("运行：" +Thread.currentThread().getName());
            }
        }, "t1");

        // 启动线程
        thread1.start();
        // thread1.run(); 主线程调用方法，并不是真的创建线程

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.println("运行：" +Thread.currentThread().getName());
            }
        };
        Thread thread2 = new Thread(runnable, "t2");
        thread2.start();

        Runnable runnable2 = () -> {
            System.out.println("运行：" +Thread.currentThread().getName());
        };
        Thread thread3 = new Thread(runnable2, "t3");
        thread3.start();

        // 创建任务对象
        FutureTask<Integer> futureTask = new FutureTask<>(() -> {
            System.out.println("运行：" +Thread.currentThread().getName());
            return 100;
        });
        // 参数1 是任务对象，参数2 是线程名称，推荐
        new Thread(futureTask, "t4").start();
        // 主线程阻塞，同步等待 task 执行完毕的结果
        Integer result = futureTask.get();
        System.out.println(result);

    }
}
